package com.aipartner.controller;

import com.aipartner.common.Result;
import com.aipartner.dto.ExampleChatRequest;
import com.aipartner.dto.ExampleDetailResponse;
import com.aipartner.entity.AiImageExampleChat;
import com.aipartner.entity.AiImageExample;
import com.aipartner.entity.UserWork;
import com.aipartner.mapper.AiImageExampleMapper;
import com.aipartner.mapper.UserFavoriteMapper;
import com.aipartner.mapper.UserWorkMapper;
import com.aipartner.service.AiImageExampleChatService;
import com.aipartner.service.UserWorkLikeService;
import com.aipartner.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.Map;

/**
 * 用户作品控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user-works")
public class UserWorksController {

    @Autowired
    private AiImageExampleChatService chatService;
    
    @Autowired
    private UserWorkMapper userWorkMapper;
    
    @Autowired
    private AiImageExampleMapper exampleMapper;
    
    @Autowired
    private UserWorkLikeService userWorkLikeService;
    
    @Autowired
    private UserFavoriteMapper userFavoriteMapper;

    /**
     * 获取用户作品详情（包含评论）
     */
    @GetMapping("/{id}/detail")
    public Result<ExampleDetailResponse> getUserWorkDetail(
            @PathVariable String id,
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @RequestParam(defaultValue = "20") @Min(1) Integer size) {
        
        try {
            Long workId = Long.parseLong(id);
            Long currentUserId = UserContext.getCurrentUserId();
            
            // 先从ai_image_examples表中查询（新的用户作品）
            AiImageExample example = exampleMapper.selectById(workId);
            if (example != null && example.getUserId() != null) {
                log.info("从ai_image_examples表找到用户作品: workId={}, userId={}", workId, example.getUserId());
                
                // 增加查看次数 - 只更新viewCount字段避免数据损坏
                int currentViewCount = (example.getViewCount() == null ? 0 : example.getViewCount()) + 1;
                example.setViewCount(currentViewCount);
                
                // 使用update wrapper只更新viewCount字段，避免更新其他字段导致BLOB数据损坏
                com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<AiImageExample> updateWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<>();
                updateWrapper.eq("id", workId).set("view_count", currentViewCount);
                exampleMapper.update(null, updateWrapper);
                
                // 创建详情响应
                ExampleDetailResponse response = new ExampleDetailResponse();
                response.setExample(example);
                
                // 获取评论数据
                try {
                    com.baomidou.mybatisplus.core.metadata.IPage<AiImageExampleChat> chatPage = 
                        chatService.getChatPage(workId, page, size, currentUserId);
                    response.setChatList(chatPage.getRecords());
                    response.setTotal(chatPage.getTotal());
                } catch (Exception e) {
                    log.error("获取用户作品评论失败: workId={}", workId, e);
                    response.setChatList(new java.util.ArrayList<>());
                    response.setTotal(0L);
                }
                
                return Result.success(response);
            }
            
            // 如果在ai_image_examples表中找不到，再从user_works表查询（历史用户作品）
            UserWork userWork = userWorkMapper.selectById(workId);
            if (userWork == null) {
                log.warn("用户作品不存在: workId={}", workId);
                return Result.fail("用户作品不存在");
            }
            
            log.info("从user_works表找到历史用户作品: workId={}, userId={}", workId, userWork.getUserId());
            
            // 增加查看次数
            userWorkMapper.incrementViewCount(workId);
            
            // 为用户作品创建详情响应
            ExampleDetailResponse response = new ExampleDetailResponse();
            
            // 创建AiImageExample格式的数据
            AiImageExample legacyExample = new AiImageExample();
            legacyExample.setId(userWork.getId());
            legacyExample.setTitle(userWork.getTitle());
            legacyExample.setImageUrl(userWork.getImageUrl());
            legacyExample.setPrompt(userWork.getPrompt());
            legacyExample.setStyle(userWork.getStyle());
            legacyExample.setSize(userWork.getSize());
            legacyExample.setUserId(userWork.getUserId());
            legacyExample.setLikeCount(userWork.getLikeCount());
            legacyExample.setViewCount(userWork.getViewCount());
            legacyExample.setCreateTime(userWork.getCreateTime());
            legacyExample.setUpdateTime(userWork.getUpdateTime());
            
            response.setExample(legacyExample);
            
            // 获取评论数据
            try {
                com.baomidou.mybatisplus.core.metadata.IPage<AiImageExampleChat> chatPage = 
                    chatService.getChatPage(workId, page, size, currentUserId);
                response.setChatList(chatPage.getRecords());
                response.setTotal(chatPage.getTotal());
            } catch (Exception e) {
                log.error("获取历史用户作品评论失败: workId={}", workId, e);
                response.setChatList(new java.util.ArrayList<>());
                response.setTotal(0L);
            }
            
            return Result.success(response);
        } catch (NumberFormatException e) {
            return Result.fail("无效的作品ID格式");
        }
    }

    /**
     * 删除用户作品
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUserWork(@PathVariable String id) {
        try {
            Long workId = Long.parseLong(id);
            Long currentUserId = UserContext.getCurrentUserId();
            
            if (currentUserId == null) {
                return Result.fail("用户未登录");
            }
            
            // 查询用户作品
            UserWork work = userWorkMapper.selectById(workId);
            if (work == null) {
                return Result.fail("作品不存在");
            }
            
            // 检查是否是作品所有者
            if (!currentUserId.equals(work.getUserId())) {
                return Result.fail("无权限删除此作品");
            }
            
            // 删除作品（数据库事务会保证一致性）
            int deleted = userWorkMapper.deleteById(workId);
            if (deleted > 0) {
                // 删除所有相关的收藏记录（保护用户隐私）
                try {
                    int deletedFavorites = userFavoriteMapper.deleteByContentTypeAndId("user_work", workId.toString());
                    log.info("删除作品 {} 成功，同时删除了 {} 条收藏记录", workId, deletedFavorites);
                } catch (Exception e) {
                    log.warn("删除作品 {} 的收藏记录时出现警告: {}", workId, e.getMessage());
                    // 不影响主要删除操作的结果
                }
                return Result.success(null);
            } else {
                return Result.fail("删除失败");
            }
            
        } catch (NumberFormatException e) {
            return Result.fail("无效的作品ID格式");
        } catch (Exception e) {
            return Result.fail("删除失败：" + e.getMessage());
        }
    }

    /**
     * 发布评论
     */
    @PostMapping("/{id}/chat")
    public Result<AiImageExampleChat> publishComment(
            @PathVariable String id,
            @Valid @RequestBody ExampleChatRequest request) {
        
        try {
            Long workId = Long.parseLong(id);
            Long userId = UserContext.getCurrentUserId();
            
            if (userId == null) {
                return Result.fail("请先登录");
            }
            
            // 检查用户作品是否存在（先检查ai_image_examples表，再检查user_works表）
            AiImageExample example = exampleMapper.selectById(workId);
            UserWork userWork = null;
            if (example == null || example.getUserId() == null) {
                userWork = userWorkMapper.selectById(workId);
                if (userWork == null) {
                    return Result.fail("用户作品不存在");
                }
            }
            
            // 发布评论（复用现有的评论服务）
            AiImageExampleChat chat = chatService.publishChat(workId, request, userId);
            return Result.success(chat);
            
        } catch (NumberFormatException e) {
            return Result.fail("无效的作品ID格式");
        }
    }

    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/chat/{id}/like")
    public Result<Map<String, Object>> toggleCommentLike(@PathVariable Long id) {
        Long userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return Result.fail("请先登录");
        }
        
        chatService.toggleLike(id, userId);
        Map<String, Object> likeInfo = chatService.getLikeInfo(id, userId);
        
        return Result.success(likeInfo);
    }

    /**
     * 获取评论点赞信息
     */
    @GetMapping("/chat/{id}/like")
    public Result<Map<String, Object>> getCommentLikeInfo(@PathVariable Long id) {
        Long userId = UserContext.getCurrentUserId();
        Map<String, Object> likeInfo = chatService.getLikeInfo(id, userId);
        return Result.success(likeInfo);
    }

    /**
     * 点赞/取消点赞用户作品
     */
    @PostMapping("/{id}/like")
    public Result<Map<String, Object>> toggleWorkLike(@PathVariable String id) {
        try {
            Long workId = Long.parseLong(id);
            Long userId = UserContext.getCurrentUserId();
            
            if (userId == null) {
                return Result.fail("请先登录");
            }
            
            // 检查用户作品是否存在（先检查ai_image_examples表，再检查user_works表）
            AiImageExample example = exampleMapper.selectById(workId);
            UserWork userWork = null;
            if (example == null || example.getUserId() == null) {
                userWork = userWorkMapper.selectById(workId);
                if (userWork == null) {
                    return Result.fail("用户作品不存在");
                }
            }
            
            // 切换点赞状态
            userWorkLikeService.toggleLike(workId, userId);
            
            // 获取最新的点赞信息
            Map<String, Object> likeInfo = userWorkLikeService.getLikeInfo(workId, userId);
            
            return Result.success(likeInfo);
            
        } catch (NumberFormatException e) {
            return Result.fail("无效的作品ID格式");
        } catch (Exception e) {
            return Result.fail("点赞操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户作品点赞信息
     */
    @GetMapping("/{id}/like-info")
    public Result<Map<String, Object>> getWorkLikeInfo(@PathVariable String id) {
        try {
            Long workId = Long.parseLong(id);
            Long userId = UserContext.getCurrentUserId();
            
            // 检查用户作品是否存在（先检查ai_image_examples表，再检查user_works表）
            AiImageExample example = exampleMapper.selectById(workId);
            UserWork userWork = null;
            if (example == null || example.getUserId() == null) {
                userWork = userWorkMapper.selectById(workId);
                if (userWork == null) {
                    return Result.fail("用户作品不存在");
                }
            }
            
            // 获取点赞信息
            Map<String, Object> likeInfo = userWorkLikeService.getLikeInfo(workId, userId);
            
            return Result.success(likeInfo);
            
        } catch (NumberFormatException e) {
            return Result.fail("无效的作品ID格式");
        }
    }
}
